package com.sce.core.service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.sce.core.entity.AuthorityEntity;
import com.sce.core.entity.UserEntity;
import com.sce.core.jpa.UserJPA;


@Component("UserService")
public class UserService implements UserDetailsService {
	
	
	@Autowired
	private UserJPA userJPA;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		
		UserEntity userEntity = userJPA.findByUserEntityNameCaseInsensitive(username.toLowerCase());
		if(null == userEntity) {
			throw new UsernameNotFoundException("user "+username+" was not found int the database");
		}
		
		//获取用户的所有权限并且SpringSecurity需要的集合
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		for(AuthorityEntity authority : userEntity.getAuthorities()) {
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getRoleName());
			grantedAuthorities.add(grantedAuthority);
		}
		 //返回一个SpringSecurity需要的用户对象
		return new User(userEntity.getUsername(),userEntity.getPassword(),grantedAuthorities);
	}

}
